<template>
  <div class="timeline-chart" ref="chartRef" style="width: 100%; height: 350px;"></div>
</template>

<script setup>
import { onMounted, ref, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref(null)
let chartInstance = null

// 生成最近7天的日期字符串数组
function getLast7Days() {
  const arr = [];
  const today = new Date();
  for (let i = 6; i >= 0; i--) {
    const d = new Date(today);
    d.setDate(today.getDate() - i);
    arr.push(d.toISOString().slice(0, 10));
  }
  return arr;
}
const dateArr = getLast7Days();

const option = {
  tooltip: {
    trigger: 'axis',
    backgroundColor: '#fff',
    borderColor: '#ccc',
    borderWidth: 1,
    textStyle: { color: '#333' },
    formatter: params => {
      let str = `${params[0].axisValue}<br/>`
      params.forEach(item => {
        str += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background:${item.color}"></span>${item.seriesName}: ${item.data}<br/>`
      })
      return str
    }
  },
  legend: {
    top: 10,
    data: ['文章', '评论', '留言'],
    icon: 'circle'
  },
  grid: {
    left: 40,
    right: 40,
    top: 50,
    bottom: 40
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: dateArr
  },
  yAxis: {
    type: 'value',
    min: 0.2,
    max: 1.0,
    interval: 0.2,
    axisLabel: {
      formatter: value => `${(value * 5000).toFixed(0)}`
    }
  },
  series: [
    {
      name: '文章',
      type: 'line',
      data: [0.1, 0.15, 0.2, 0.3, 0.18, 0.17, 0.2],
      smooth: true, 
      symbol: 'circle',
      symbolSize: 7,
      itemStyle: { color: '#5B9EFF' },
      lineStyle: { color: '#5B9EFF', width: 2 },
      label: {
        show: true,
        position: 'top',
        color: '#5B9EFF',
        formatter: v => v.value > 0 ? v.value.toFixed(3) : ''
      }
    },
    {
      name: '评论',
      type: 'line',
      data: [0.2, 0.3, 0.5, 0.7, 0.9, 1.0, 0.8],
      smooth: true, 
      symbol: 'circle',
      symbolSize: 7,
      itemStyle: { color: '#FF6B81' },
      lineStyle: { color: '#FF6B81', width: 2 },
      label: { show: false }
    },
    {
      name: '留言',
      type: 'line',
      data: [0.2, 0.25, 0.3, 0.4, 0.6, 0.7, 0.9],
      smooth: true, 
      symbol: 'circle',
      symbolSize: 7,
      itemStyle: { color: '#4BC18E' },
      lineStyle: { color: '#4BC18E', width: 2 },
      label: { show: false }
    }
  ]
}

onMounted(() => {
  chartInstance = echarts.init(chartRef.value)
  chartInstance.setOption(option)
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  if (chartInstance) chartInstance.dispose()
})

function resizeChart() {
  if (chartInstance) chartInstance.resize()
}
</script>

<style scoped>
.timeline-chart {
  width: 100%;
  height: 350px;
}
</style>
